package com.ruoyi.workflow.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.domain.CarPackageAuditVo;
import com.ruoyi.workflow.service.IBpmnNodeService;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.ITaskToDoService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.catalina.security.SecurityUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskToDoServiceImpl implements ITaskToDoService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnNodeService bpmnNodeService;
    @Autowired
    private ISysUserService sysUserService;
    @Override
    public TableDataInfo selectCarPackageAuditList(CarPackageAudit carPackageAudit) {
        TableDataInfo info = new TableDataInfo();
        info.setCode(HttpStatus.SUCCESS);
        info.setMsg("查询成功");

        //2.获取当前登录的用户id
        String  username = SecurityUtils.getUsername();
        //3.基于当前登录用户，去查该用户为候选人/负责人的任务数量
        long total = taskService.createTaskQuery()
                .taskCandidateOrAssigned(username)
                .orderByTaskCreateTime()
                .asc()
                .count();
        if (total==0){
            //4.如果数量为0，直接返回空数据
            info.setTotal(total);
            info.setRows(Collections.emptyList());
            return info;
        }
        //1.接受前端分页条件
        PageDomain pageDomain = TableSupport.buildPageRequest();
        //计算分页开始索引位置（当前页-1）*每页显示条数
        int startIndex = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        //5.基于当前登录用户去查询用户候选人/负责人的任务列表
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateOrAssigned(username)
                .orderByTaskCreateTime()
                .asc()
                .listPage(startIndex, pageDomain.getPageSize());
        List<CarPackageAudit> audits = new ArrayList<>();
        //6.遍历任务列表
        for (Task task : tasks) {
            //7.获取该任务的流程实列 id ，查询流程实列对象，得到业务标识
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            //8.通过业务标识，查询审核记录对象
            String businessKey = processInstance.getBusinessKey();
            CarPackageAudit audit = carPackageAuditService.getById(businessKey);
            CarPackageAuditVo vo = new CarPackageAuditVo();
            //9.为审核记录设置当前任务名称/id，当前审核人
            BeanUtils.copyBeanProp(vo,audit);
            vo.setTaskName(task.getName());
            vo.setTaskId(task.getId());
            //查询创建者
            SysUser sysUser = sysUserService.selectUserById(Long.parseLong(audit.getCreatorId()));
            vo.setCreatorName(sysUser.getNickName());
            //通过任务key查询候选人
            List<SysUser> users = bpmnNodeService.selectUserIdsByNodeKey(task.getTaskDefinitionKey());
            List<String> nickName = users.stream().map(SysUser::getNickName).collect(Collectors.toList());
            vo.setAuditors(JSON.toJSONString(nickName));
            //10.将当前审核记录对象放到返回的集合中
            audits.add(vo);
        }
        info.setRows(audits);
        //11.最终返回审核记录列表集合
        return info;
    }
}
